package com.example.demo.zip.controller;

import com.example.demo.zip.SevenZipUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author: zjq
 * @Date: create in 2022/9/14 15:13
 */
@RestController
@RequestMapping("/api/zip")
@Api(value = "zipcontroller", tags = {"zip生成"})
public class SevenzTestController {
    //7Z的压缩解压功能

    //待压缩文件夹/文件名
    String srcPath = "C:\\Users\\THINK\\Downloads\\test";
    //生成的压缩包名字
    String dest7zFilePath = "C:\\Users\\THINK\\Downloads\\7zTest.7z";
    //解压路径
    String destPath = "C:\\Users\\THINK\\Downloads\\un7z";

    @PostMapping("compress7z")
    @ApiOperation(value = "7z压缩")
    public void compress7z(HttpServletResponse response) throws IOException {
        Long start = System.currentTimeMillis();
        // 浏览器响应
        // 浏览器响应返回
        response.reset();
        // 设置response的header，response为HttpServletResponse接收输出流
        response.setContentType("application/octet-stream");
        String sevenzFileName = "7zFile-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern(
                "yyyyMMddHHmmss")) + ".7z";
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(sevenzFileName, "UTF-8"));

        // 压缩为7z
        SevenZipUtil.compress7z(srcPath, dest7zFilePath);


        // 将压缩好的7z响应给浏览器
        File file = new File(dest7zFilePath);
        if (null != file && file.isFile()) {
            ServletOutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            int len = -1;
            // 将源文件写入到输出流
            byte[] buf = new byte[1024];
            while ((len = bis.read(buf)) != -1) {
                os.write(buf, 0, len);
            }

            bis.close();
            fis.close();
            os.close();
        }
        Long end = System.currentTimeMillis();
        System.out.println("start" + start);
        System.out.println("end" + end);
        System.out.println("start-end" + (start - end));

    }


    @ApiOperation(value = "7z解压")
    @PostMapping("unCompress7z")
    public void unCompress7z() throws Exception {
        // 解压
        SevenZipUtil.unCompress7z(dest7zFilePath, destPath);
    }
}
